<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/common :: head}"></head>
<body>
  <div class="portletBody container-fluid">
    <div th:replace="~{fragments/common :: menu('list')}"></div>

    <div th:if="${success}" class="sak-banner-success" role="status" th:text="${success}">Success</div>
    <div th:if="${alert}" class="sak-banner-error" role="alert" th:text="${alert}">Error</div>

    <div class="d-flex justify-content-between align-items-center mb-3">
      <h1 class="h3 mb-0" th:text="#{poll_list_title}">Polls</h1>
    </div>

    <div class="sak-banner-info" role="status" th:if="${#lists.isEmpty(polls)}" th:text="#{poll_list_empty}">
      No polls have been created yet.
    </div>

    <form th:if="${!#lists.isEmpty(polls)}" method="post" th:action="@{/polls/bulk}">
      <input type="hidden" name="siteId" th:value="${siteId}" />

      <div class="table-responsive">
        <table class="table table-striped table-hover align-middle">
          <caption class="visually-hidden" th:text="#{poll_list_summary}">Poll summary</caption>
          <thead>
            <tr>
              <th scope="col">
                <a href="#" class="link-body-emphasis text-decoration-none" th:text="#{poll_question_title}">Question</a>
              </th>
              <th scope="col">
                <a href="#" class="link-body-emphasis text-decoration-none" th:text="#{poll_open_title}">Opening</a>
              </th>
              <th scope="col">
                <a href="#" class="link-body-emphasis text-decoration-none" th:text="#{poll_close_title}">Closing</a>
              </th>
              <th scope="col" th:text="#{poll_result_title}">Results</th>
              <th scope="col" class="text-nowrap">
                <div class="form-check m-0" th:if="${renderDelete}">
                  <input type="checkbox" id="remove-all" />
                  <label class="form-check-label" for="remove-all" th:text="#{poll_select_title_all}">Select all</label>
                </div>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr th:each="poll : ${polls}">
              <td>
                <div class="d-flex flex-column gap-1">
                  <a th:if="${poll.votable}" class="fw-semibold" th:href="@{'/voteQuestion'(pollId=${poll.id})}" th:text="${poll.text}">
                    Poll question
                  </a>
                  <span th:if="${!poll.votable}" th:text="${poll.optionCount == 0 ? poll.text + ' (' + #messages.msgOrNull('poll_no_options') + ')' : poll.text}">
                    Poll question
                  </span>
                  <div class="d-flex flex-wrap gap-2">
                    <a th:if="${poll.editable}" class="btn btn-outline-secondary btn-sm" role="button" th:href="@{'/voteAdd'(pollId=${poll.id})}" th:text="#{action_revise_poll}">
                      Edit
                    </a>
                  </div>
                </div>
              </td>
              <td>
                <span th:if="${poll.voteOpenDisplay}" th:text="${poll.voteOpenDisplay}" th:attr="data-sort=${poll.voteOpenSortKey}">Opening</span>
                <span th:if="${poll.voteOpenDisplay == null}">&nbsp;</span>
              </td>
              <td>
                <span th:if="${poll.voteCloseDisplay}" th:text="${poll.voteCloseDisplay}" th:attr="data-sort=${poll.voteCloseSortKey}">Closing</span>
                <span th:if="${poll.voteCloseDisplay == null}">&nbsp;</span>
              </td>
              <td>
                <a th:if="${poll.resultsVisible}" th:href="@{'/voteResults'(pollId=${poll.id})}" th:text="#{action_view_results}">Results</a>
              </td>
              <td>
                <div class="form-check" th:if="${poll.deletable}">
                  <input type="checkbox" th:id="${'delete-' + poll.id}" name="deleteIds" th:value="${poll.id}" />
                  <label class="form-check-label visually-hidden" th:for="${'delete-' + poll.id}" th:text="${#messages.msg('delete_poll_tooltip', poll.text)}">Delete</label>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="d-flex gap-2 mt-3 act" th:if="${renderDelete}">
          <input id="delete-polls" type="button" name="action" value="delete" th:value="#{poll_list_delete}"/>
          <input id="reset-polls-votes" type="button" name="action" value="reset" th:value="#{poll_list_reset}"/>
      </div>
    </form>

    <!-- Delete Confirmation Modal -->
    <div id="deleteConfirmationModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="deleteConfirmationModalTitle">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="deleteConfirmationModalTitle" th:text="#{poll_list_delete_confirm_title}">Confirm Delete</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="sak-banner-warn" role="alert" th:text="#{poll_list_delete_confirm_message}">Are you sure you want to delete the selected polls? This action cannot be undone.</div>
          </div>
          <div class="modal-footer act">
            <button type="button" class="btn btn-primary" id="confirmDelete" data-bs-dismiss="modal" th:text="#{poll_list_delete_confirm}">Delete</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" th:text="#{poll_list_cancel}">Cancel</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Reset Confirmation Modal -->
    <div id="resetConfirmationModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="resetConfirmationModalTitle">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="resetConfirmationModalTitle" th:text="#{poll_list_reset_confirm_title}">Confirm Reset</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="sak-banner-warn" role="alert" th:text="#{poll_list_reset_confirm_message}">Are you sure you want to reset votes for the selected polls? This action cannot be undone.</div>
          </div>
          <div class="modal-footer act">
            <button type="button" class="btn btn-primary" id="confirmReset" data-bs-dismiss="modal" th:text="#{poll_list_reset_confirm}">Reset</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" th:text="#{poll_list_cancel}">Cancel</button>
          </div>
        </div>
      </div>
    </div>

  </div>
  <script type="module">
  const selectAll = document.getElementById('remove-all');
  const deleteButton = document.getElementById('delete-polls');
  const resetButton = document.getElementById('reset-polls-votes');
  const checkboxes = Array.from(document.querySelectorAll('input[name="deleteIds"]'));
  const form = document.querySelector('form[action*="/polls/bulk"]');

  const updateState = () => {
    const checked = checkboxes.filter(cb => cb.checked);
    const disabled = checked.length === 0;
    if (deleteButton) {
      deleteButton.disabled = disabled;
      deleteButton.setAttribute('aria-disabled', String(disabled));
      deleteButton.classList.toggle('active', !disabled);
    }
    if (resetButton) {
      resetButton.disabled = disabled;
      resetButton.setAttribute('aria-disabled', String(disabled));
      resetButton.classList.toggle('active', !disabled);
    }
    if (selectAll) {
      selectAll.checked = checked.length === checkboxes.length && checkboxes.length > 0;
    }
  };
  if (selectAll) {
    selectAll.addEventListener('change', (event) => {
      checkboxes.forEach(cb => cb.checked = event.target.checked);
      updateState();
    });
  }

  checkboxes.forEach(cb => cb.addEventListener('change', updateState));
  updateState();

  // Handle delete button click
  if (deleteButton) {
    deleteButton.addEventListener('click', (event) => {
      event.preventDefault();
      const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmationModal'));
      deleteModal.show();
    });
  }

  // Handle reset button click
  if (resetButton) {
    resetButton.addEventListener('click', (event) => {
      event.preventDefault();
      const resetModal = new bootstrap.Modal(document.getElementById('resetConfirmationModal'));
      resetModal.show();
    });
  }

  // Handle delete confirmation
  const confirmDeleteButton = document.getElementById('confirmDelete');
  if (confirmDeleteButton) {
    confirmDeleteButton.addEventListener('click', () => {
      if (form && deleteButton) {
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'delete';
        form.appendChild(actionInput);
        form.submit();
      }
    });
  }

  // Handle reset confirmation
  const confirmResetButton = document.getElementById('confirmReset');
  if (confirmResetButton) {
    confirmResetButton.addEventListener('click', () => {
      if (form && resetButton) {
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'reset';
        form.appendChild(actionInput);
        form.submit();
      }
    });
  }
  </script>
</body>
</html>
